package com.example.a10928.weifriend.ui.task_center

import android.app.Activity
import android.content.Intent
import android.databinding.ViewDataBinding
import android.graphics.Color
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.View
import com.example.a10928.weifriend.App
import com.example.a10928.weifriend.App.app
import com.example.a10928.weifriend.R
import com.example.a10928.weifriend.adapter.GridImageAdapter
import com.example.a10928.weifriend.databinding.ActivitySubmitTaskBinding
import com.example.a10928.weifriend.http.api.VariableName
import com.example.a10928.weifriend.http.configuration.ApiException
import com.example.a10928.weifriend.manager.FullyGridLayoutManager
import com.example.a10928.weifriend.ui.DatabindingBaseActivity
import com.example.a10928.weifriend.util.L
import com.example.a10928.weifriend.util.RxUtil
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.mylhyl.circledialog.CircleDialog
import kotlinx.android.synthetic.main.activity_personal_info.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.util.ArrayList

class SubmitTaskActivity : DatabindingBaseActivity() {

    lateinit var adapter: GridImageAdapter
    private var selectList: List<LocalMedia> = ArrayList()
    var adId: Int = -1
    var data:String=""
    override fun bindingInitData() {
        adapter = GridImageAdapter(this, addPicClickListener)
        adapter.setOnItemClickListener(listener)
        adId = intent.getIntExtra(DATA_ADVER_ID, -1)
        data=intent.getStringExtra(VariableName.DATA)
    }

    override fun bindingInitView(viewDataBinding: ViewDataBinding?) {
        var mBinding = viewDataBinding as ActivitySubmitTaskBinding
        mBinding.view = this
        setTitleText(ThemeEnum.Back_Default,"上传任务")
        mBinding.submitAddRv.adapter = adapter
        mBinding.submitAddRv.layoutManager = FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)

        supportActionBar?.hide()

        if(data.equals("3")){
            mBinding.submitBtSend.text="上传任务载图"

        }
    }

    override fun bindingGetContentView(): Int {
        return R.layout.activity_submit_task
    }

    public fun onViewClick(v: View) {
        when (v.id) {
            R.id.submit_bt_send -> {
                submitTask()
            }
            else -> {
            }
        }
    }

    fun submitTask() {

        if (selectList.size == 0 ) {
            L.t("请选择图片后在提交");return
        }

        CircleDialog.Builder()
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setTitle("确认提交")
                .setText("确认提交该任务")
                .setNegative("取消", null)
                .setPositive("确定") { v ->
                    var file = File(selectList[0]!!.compressPath)
                    val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
                    val body = MultipartBody.Part.createFormData("proof_img", file.getName(), requestBody)
                    app().bpService.submitTask(
                            toRequestBody(App.app().user.userId),
                            toRequestBody(Integer.toString(adId)),
                            body)
                            .compose(RxUtil.io2mainLoad(this))
                            .subscribe(
                                    {
                                        L.t("提交成功")
                                        this.finish()
                                    },
                                    {
                                        if (it is ApiException){
                                            if((it as ApiException).code==4001){
                                                L.t((it as ApiException).msg)
                                            }else{
                                                RxUtil.errorException(it)
                                            }
                                        }
                                    }
                            )
                }
                .configNegative { params -> params.textColor = Color.RED }
                .show(getSupportFragmentManager())

    }

    companion object {
        val DATA_ADVER_ID: String = "dataAdverId"
    }

    fun toRequestBody(value: String): RequestBody {
        return RequestBody.create(MediaType.parse("text/plain"), value)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data)
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    for (media in selectList) {
                        Log.i("图片-----》", media.path)
                    }
                    adapter.setList(selectList)
                    adapter.notifyDataSetChanged()
                }
            }
        }
    }


    private val addPicClickListener = GridImageAdapter.onAddPicClickListener { createPictureSelector() }


    private fun createPictureSelector() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .isZoomAnim(true)
                .compress(true)
                .previewEggs(true)
                .glideOverride(160, 160)
                .minimumCompressSize(500)
                .forResult(PictureConfig.CHOOSE_REQUEST)
    }

    internal var listener: GridImageAdapter.OnItemClickListener = GridImageAdapter.OnItemClickListener { position, v ->
        if (selectList.size > 0) {
            val media = selectList.get(position)
            val pictureType = media.getPictureType()
            val mediaType = PictureMimeType.pictureToVideo(pictureType)
            when (mediaType) {
                1 ->
                    // 预览图片 可自定长按保存路径
                    //PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                    PictureSelector.create(this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList)
                2 ->
                    // 预览视频
                    PictureSelector.create(this).externalPictureVideo(media.getPath())
                3 ->
                    // 预览音频
                    PictureSelector.create(this).externalPictureAudio(media.getPath())
            }
        }
    }
}